package view;

import java.rmi.RemoteException;

import javax.swing.JFrame;
import javax.swing.JTabbedPane;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

import server.FirewallSession;
/**
 * Class is singelton - only one instance exists.
 * Main FW frame:
 * 		menu - rules, logger, reg. expressions, exceptions, help 
 * 		standart buttons - finish, cancel
 */
public class MainFrame extends JFrame
{
	/**
	 * 
	 */
	private static final long serialVersionUID = 5032322274335194335L;

	/**
	 * server controller
	 */
	protected FirewallSession UI;
	
	/* Current frame */
	static private MainFrame frame = null;
	
	/**
	 * C'tor
	 */
	private MainFrame(FirewallSession ui)
	{	
		/* Frame definition */
		super("FW Manager");
		UI = ui;
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setSize(Globals.mainFrameSize);
	
		/* Frame look definition */
		String plaf = "com.sun.java.swing.plaf.windows.WindowsLookAndFeel";
		try {
			UIManager.setLookAndFeel(plaf);
			SwingUtilities.updateComponentTreeUI(this);
		} catch (final Exception e) {
			System.out.println("Look and Feel problem");
		}
	}	
	
	/**
	 * Function creates two tabs for the frame.
	 */
	public void createTabs()
	{
		final JTabbedPane tabbedPane = new JTabbedPane();
	    String[] tabs = { UserMode.standartUser, UserMode.advancedUser };

	    for(int i = 0; i < tabs.length; i++)
	    {
	    	tabbedPane.addTab(tabs[i], new UserPanel(UI));	
	    }
	    
	    getContentPane().add(tabbedPane);
	    
	    tabbedPane.addChangeListener(new ChangeListener()
	    {
			public void stateChanged(ChangeEvent event) 
			{
				String newMode = UserMode.getUserMode(tabbedPane.getModel().getSelectedIndex());
				if (newMode.equals(UserMode.advancedUser))
				{
					
					try {
						if (!UI.isExpert())
						{
							ErrorFrame.AddError("Failed to login:You have no permissions of Advanced User.",frame);
							return;
						}
					} catch (RemoteException e) {
						ErrorFrame.AddError("Failed to login:" + e.getMessage(), new JFrame());
					}
				}
				Settings.userMode = newMode;
			}});
	}
	
	/**
	 * Function returns the current frame if it exists 
	 * 		and the new frame if doesn't.
	 */
	public static MainFrame getInstance(FirewallSession ui)
	{
		if(frame == null)
		{
			frame = new MainFrame(ui);
		}
		return frame;
	}
}
